<?php

namespace app\api\service;

use app\admin\model\PoliteConfig;
use app\admin\model\PoliteStart;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Db;

class Start
{

    public static function getList($type, $pageNum, $pageSize): array
    {
        $map=[];
        if($type!=-1){
            $map[]= Db::raw('FIND_IN_SET("'.$type.'",type)');
        }
        $model=new PoliteStart();
        $list=$model->where($map)->order('order asc')->field('id,name,files,addr_name,type')->page($pageNum,$pageSize)->select();
        $list=$list->isEmpty()?[]:$list->toArray();
        return self::resetList($list,4);
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws Exception
     */
    public static function getDetail($id){
        $model=new PoliteStart();
        $map=[
            ['id','=',$id]
        ];
        $row=$model->where($map)->find();
        if($row->isEmpty()){
            throw new Exception('数据不存在');
        }
        return self::resetRow($row,self::getConfigLib($row['category']));
    }

    public static function resetRow($row,$configLib){
        if(!is_array($row)){
            $row=$row->toArray();
        }
        if(isset($row['files'])){
            $row['files']=self::resetFiles($row['files']);
        }
        if(isset($row['type'])){
            $type=explode(',',$row['type']);
            $row['type']=[];
            foreach ($type as $k1=>$v1){
                if(isset($configLib[$v1])){
                    $row['type'][]=$configLib[$v1]['config_value'];
                }
            }
        }
        if(isset($row['content'])){
            $row['content']=Article::getHtml($row['content']);
        }
        return $row;
    }
    public static function resetFiles($files){
        $data=[];
        $files=empty($files)?[]:explode('|',$files);
        foreach ($files as $k=>$v){
            $data[]=['url'=>$v];
        }
        return $data;
    }
    public static function resetList($list,$category){
        if(!is_array($list)){
            $list=$list->toArray();
        }
        $configLib=self::getConfigLib($category);
        foreach ($list as $k=>$v){
            $list[$k]=self::resetRow($v,$configLib);
        }
        return $list;
    }
    public static function getConfigLib($category): array
    {
        $model=new PoliteConfig();
        $configLib=$model->where([['config_type','=',$category]])->field('id,config_value')->select();
        $configLib=$configLib->isEmpty()?[]:$configLib->toArray();
        $data=[];
        foreach ($configLib as $k=>$v){
            $data[$v['id']]=$v;
        }
        return $data;
    }
}